
from app.chess import pika_pool
from app import dbop
from app import tools
from app.rule import ChessGame


def test_pika():
    engine, lock = pika_pool.get_engine()
    try:
        engine.stdin.write("position startpos\n")
        engine.stdin.flush()
        engine.stdin.write("go depth 18\n")
        engine.stdin.flush()
        output = pika_pool.get_engine_output(engine)
        # output = engine.stdout.readlines()
        # output, err = engine.communicate()
        # print(output)
        print("go depth 18:")
        for item in output:
            print(item)
    except Exception as e:
        print(e)
    finally:
        pika_pool.release_engine(engine, lock)


def test_best_move_transform(param):
    last_line = 'bestmove h9g7 ponder g3g4'
    last_line_part = [x.strip() for x in last_line.split(" ")]
    if last_line_part[0] == "bestmove":
        move = last_line_part[1]
        print("move:", move)


def test_chess_game(params):
    match_id = params.get('match_id')
    records = dbop.ChessGameProcessDAO.get_match_record(match_id)
    if not records:
        params["seq"] = 1
        game = ChessGame()
    else:
        params["seq"] = records[-1].seq + 1
        last_record = records[-1]
        status_json = tools.safe_json_loads(last_record.status)
        game = ChessGame(status_json)
    game.print_status()


def proc_test_api(param):
    # test_best_move_transform(param)
    test_chess_game(param)
    return {
        "error": 0
    }
